#!/bin/sh
# 此脚本用于安装oh-my-zsh

# 官方安装方式如下：
# sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
# 不过由于众所周知的原因，可能安装不成功
# 此脚本的首先尝试使用curl从github下载安装脚本
# 不成功则尝试使用git clone的方式下载安装脚本
# 下载完之后执行安装脚本

REPO=${REPO:-ohmyzsh/ohmyzsh}
REMOTE=${REMOTE:-https://github.com/${REPO}.git}
BRANCH=${BRANCH:-master}

TEMP_REPO_DIR=/tmp/.oh-my-zsh
SCRIPT_PATH=/tmp/zconf-omz-install.sh

download_install_script() {
    echo 'Downloading install script from github...'

    # 直接下载
    echo 'Trying curl...'
    if curl -L https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh -o $SCRIPT_PATH ; then
        echo "Install script saved to $SCRIPT_PATH"
        return
    fi

    # 下载失败，先clone
    echo 'Trying git clone...'
    if git clone -c core.eol=lf -c core.autocrlf=false \
        -c fsck.zeroPaddedFilemode=ignore \
        -c fetch.fsck.zeroPaddedFilemode=ignore \
        -c receive.fsck.zeroPaddedFilemode=ignore \
        --depth=1 --branch "$BRANCH" "$REMOTE" "$TEMP_REPO_DIR" ; then
        SCRIPT_PATH="$TEMP_REPO_DIR/tools/install.sh"
        echo "Install script saved to $SCRIPT_PATH"
        return
    fi
    # 两次尝试均不成功，直接退出
    echo "Failed to fetch install script."
    exit -1
}

download_install_script && sh $SCRIPT_PATH

rm -rf $TEMP_REPO_DIR
